#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Licensed Materials - Property of tenxcloud.com
# (C) Copyright 2020 TenxCloud. All Rights Reserved.
# 2020-05-31 @author lizhen

from flask.json import JSONEncoder as FlaskJSONEncoder
from datetime import datetime
from enum import Enum

import uuid
import os


class JSONEncoder(FlaskJSONEncoder):

    def default(self, obj):

        if isinstance(obj, datetime):
            return obj.isoformat()

        if isinstance(obj, Enum):
            return obj.name

        if callable(getattr(obj, "to_dict", None)):
            return obj.to_dict()

        try:
            iterable = iter(obj)
        except TypeError:
            pass
        else:
            return list(iterable)

        return JSONEncoder.default(self, obj)


def short_uuid():
    return str(uuid.uuid4())[:8]


def save_file(file, data_set_id, data_set_folder):
    _, suffix = os.path.splitext(file.filename)
    file_id = short_uuid()
    mask = file_id + suffix
    full_path = os.path.join(data_set_folder, mask)

    file.save(full_path)

    return {
        'id': file_id,
        'create_at': datetime.now(),
        'filename': file.filename,
        'suffix': suffix,
        'mask': mask,
        'data_set_id': data_set_id,
    }
